// pages/ScenicArea/ScenicAreaCommitPage/index.js
var common = require("../../../public.js");
Page({

    /**
     * 页面的初始数据
     */
    data: {
        buyerList: [], //购票人列表
        selectedBuyerList: [], // 选中的购票人
        couponList: [], // 可用优惠券列表
        currentCoupon: '', //选中的优惠券
        showBuyerPanel: false,
        showCouponsPanel: false,
        isLoadingBusy: false,
        cardId: "",
        xcTimeId: '',
        totalPrice: 0,
        flags: true, //控制开关
        discountsMoney: 0,//优惠金额
        storeType: '',

    },
    // 券确定
    ComPany_submit() {
        this.setData({
            showCouponsPanel: false,
        })
        // console.log(this.data.comL, "dkdddiokdjd")
    },
    click_company(e) {
        var that = this
        let {
            index,
            item
        } = e.currentTarget.dataset
        // ticketPrice*ticketNum < item.discountsMoney
        if (that.data.ticketPrice * that.data.ticketNum < item.exceedMoney && that.data.flags && that.data.couponList.length != 1) {
            common.showToast('商品总额不能低于满减金额')
            return
        }
        if (that.data.flags && that.data.ticketPrice * that.data.ticketNum < item.exceedMoney && that.data.couponList.length == 1) {
            common.showToast('商品总额不能低于满减金额')
            return
        }
        if (!that.data.flags && item.isSelect != true) {
            common.showToast('此为单选，请先取消选中')
            return
        }
        for (var i = 0; i < this.data.couponList.length; i++) {
            if (i == index) {
                this.data.couponList[i].isSelect = !this.data.couponList[i].isSelect
            } else {
                this.data.couponList[i].isSelect = false
            }
        }
        if (!item.isSelect) {
            console.log("选中")
            var totalPrice = item.discountsMoney //单选的优惠金额

            var ToTAL = ((this.data.totalPrice * 100) - (item.discountsMoney * 100)) / 100
            console.log(ToTAL)

        } else {

            var totalPrice = 0

            var ToTAL = ((this.data.totalPrice * 100) + (item.discountsMoney * 100)) / 100

        }
        this.setData({
            discountsMoney: totalPrice,
            couponList: this.data.couponList,
            totalPrice: ToTAL,
        }, () => {

            var inde = this.data.couponList.findIndex(t => t.isSelect == true)
            var coupObj = inde != -1 ? this.data.couponList[inde] : ''
            that.setData({
                currentCoupon: coupObj.couponNo
            })
            if (this.data.couponList.findIndex(targrt => targrt.isSelect == true) == -1) {
                that.setData({
                    flags: true
                })

            } else {
                that.setData({
                    flags: false
                })
            }
        })

    },
    onLoad: function (options) {
        console.log(options, 66666)
        let that = this
        wx.getStorage({
            key: 'user',
            success: function (res) {
                that.setData({
                    userInfo: res.data.user,
                    token: res.data.token,
                    openid: res.data.openid,
                    ticketId: options.ticketId,
                    storeId: options.storeId,
                    ticketName: options.ticketName,
                    storeName: options.storeName,
                    cardId: options.cardId ? options.cardId : '',
                    ticketPrice: parseFloat(options.ticketPrice).toFixed(2),
                    ticketNum: options.ticketNum,
                    ticketTimeId: options.ticketTimeId,
                    enterDate: options.enterDate,
                    enterWeekday: options.enterWeekday,
                    startTime: options.startTime,
                    endTime: options.endTime,
                    storeType: options.storeType,
                    xcTimeId: options.xcTimeId == 'undefined' ? '' : options.xcTimeId,
                    totalPrice: (parseFloat(options.ticketPrice * 100 * options.ticketNum) / 100)
                }, _ => {
                    console.log(that.data.totalPrice)
                    that.getBuyerList()
                    that.getCoupon()
                })
            },
        })
    },
    getBuyerList() { // 获取购票人列表
        let that = this
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.post("/scenicTicket/ticketBuyer/getScenicTicketBuyerList", tempJson, function (res) {
            if (res.status === 200) {

                that.setData({
                    buyerList: res.data
                })
            }
        })
    },
    getCoupon() { // 获取景区门票可用优惠券
        const that = this
        const tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            ticketId: that.data.ticketId,
            buyNums: that.data.ticketNum
        }
        common.post("/order/getUserCityDiscountCouponForScenicTicket", tempJson, function (res) {
            if(res.data){
                for (let i = 0; i < res.data.length; i++) {
                    res.data[i].isSelect = false
                }
            }
        
            if (res.status === 200) {
                that.setData({
                    couponList: res.data
                })
            }
        })
    },
    selectBuyer(e) {
        console.log(e)
        let {
            index,
            item
        } = e.currentTarget.dataset

        let arrIndex = this.data.selectedBuyerList.indexOf(index)
        console.log(arrIndex, "1111111")
        if (arrIndex != -1) { // 有

            let arr = this.data.selectedBuyerList
            arr.splice(arrIndex, 1)
            console.log(arr)
            this.setData({
                selectedBuyerList: arr
            })

        } else { // 没有
            if (this.data.selectedBuyerList.length < this.data.ticketNum) {
                this.setData({
                    selectedBuyerList: [...this.data.selectedBuyerList, index]
                })
            }
        }
    },
    // selectCoupon(e) {
    //     let {
    //         index,
    //         item
    //     } = e.currentTarget.dataset
    //     if (index == (this.data.currentCoupon.hasOwnProperty('index') ? this.data.currentCoupon.index : null)) { //再次点击已选中则取消选中
    //         this.setData({
    //             currentCoupon: '',
    //             totalPrice: this.data.ticketPrice * 100 * this.data.ticketNum
    //         })
    //     } else {
    //         this.setData({
    //             showCouponsPanel: false,
    //             totalPrice: this.data.totalPrice - item.discountsMoney * 100,
    //             currentCoupon: {
    //                 index,
    //                 item
    //             }
    //         })
    //     }
    // },
    twos() {
        console.log("chuali")
        console.log(this.data.cardId)
    },
    impower() {
        var that = this
        wx.requestSubscribeMessage({
            // 调起消息订阅界面
            tmplIds: ['yIwx-H3x_RN65DH9LgmqxbLLhZONjEgYxQDIuRCOkIw', 'x2-i5Zf_jkdQJZJiLv-2e0TZZnAksfzp1RnWxP8dM0U'],
            success(res) {
                console.log('订阅消息 成功 ');
                console.log(res)
            },
            fail(er) {
                console.log("订阅消息 失败 ");
                console.log(res)
            },
            complete: (errMsg) => {
                this.fns()

            }
        })

    },
    // 下单和支付
    fns() {
        var that = this

        if (that.data.selectedBuyerList.length != that.data.ticketNum) {
            wx.showToast({
                title: '请添加' + that.data.ticketNum + '位购票人信息',
                icon: 'none'
            })
            return;
        }
        let buyerList = []
        that.data.selectedBuyerList.map(index => {
            let buyerItem = {
                name: that.data.buyerList[index].name,
                phone: that.data.buyerList[index].phone,
                certificateNo: that.data.buyerList[index].certificateNo,
            }
            buyerList.push(buyerItem)
        })
        if (that.data.cardId == '') {
            console.log("buzou")
            var tempJson = {
                userId: that.data.userInfo.id,
                // cardId:that.data.cardId,
                token: that.data.token,
                storeId: that.data.storeId,
                couponNo: '',
                // cityCouponNo: that.data.currentCoupon ? that.data.currentCoupon.item.couponNo : '',
                // cityCouponNo: that.data.currentCoupon,
                cityCouponNo: that.data.currentCoupon ? that.data.currentCoupon : '',
                payment: that.data.totalPrice,
                ticketId: that.data.ticketId,
                ticketName: that.data.ticketName,
                ticketPrice: that.data.ticketPrice,
                ticketNum: that.data.ticketNum,
                ticketTimeId: that.data.ticketTimeId,
                enterDate: that.data.enterDate,
                enterWeekday: that.data.enterWeekday,
                buyerList: buyerList,
                xcTimeId: that.data.xcTimeId,
            }

            // common.postJson("/ticketOrder/buyTicket", tempJson, function (res) {
            common.postJson("/ticketOrder/buyTicketByChinaumsFYPlatform", tempJson, function (res) {
                if (res.status == 200) {
                    if (that.data.totalPrice == 0) {
                        wx.navigateTo({
                            url: '/pages/ScenicArea/ScenicAreaCommitPage/paySuccess/index?payment=' + that.data.totalPrice
                        })
                    } else {
                        that.wxpay(res.data)
                    }
                } else {
                    common.showRequestErrMsg(res)
                }
            })
            return
        } else if (that.data.cardId != '') { //会员卡
            console.log("buzou")
            var tempJson = {
                userId: that.data.userInfo.id,
                cardId: that.data.cardId,
                token: that.data.token,
                storeId: that.data.storeId,
                couponNo: '',
                cityCouponNo: that.data.currentCoupon ? that.data.currentCoupon.item.couponNo : '',
                payment: that.data.totalPrice,
                ticketId: that.data.ticketId,
                ticketName: that.data.ticketName,
                ticketPrice: that.data.ticketPrice,
                ticketNum: that.data.ticketNum,
                ticketTimeId: that.data.ticketTimeId,
                enterDate: that.data.enterDate,
                enterWeekday: that.data.enterWeekday,
                buyerList: buyerList
            }
            // common.postJson("/ticketOrder/buyTicket", tempJson, function (res) {
            common.postJson("/ticketOrder/buyTicketByChinaumsFYPlatform", tempJson, function (res) {
                if (res.status == 200) {
                    if (that.data.totalPrice == 0) {
                        wx.navigateTo({
                            url: '/pages/ScenicArea/ScenicAreaCommitPage/paySuccess/index?payment=' + that.data.totalPrice + '&cardId=' + that.data.cardId,
                        })
                    } else {
                        that.wxpay(res.data)
                    }
                } else {
                    common.showRequestErrMsg(res)
                }
            })

        }

    },
    onSubmit() { // 提交订单
        const that = this
        // 判断是否场馆，场馆不显示提示显示
        // if(this.data.storeType==6){
        //     that.impower()
        // }else{
        console.log(this.data.cardId)
        if (this.data.cardId) {
            that.impower()
            return
        }
        this.fns()
        // 
        // }

    },

    wxpay(orderId) { // 支付
        let that = this
        let tempJson = {
            orderId,
            userId: that.data.userInfo.id,
            token: that.data.token,
            xcxOpenid: that.data.openid
            // openid: that.data.openid
        }
        // common.wxPayRequest("/wxxcxPayForScenicTicket", tempJson, function (res)
        common.wxPayRequest("/wxxcxPayScenicTicketForFYPlatformByChinaUms", tempJson, function (res) {
            if (res.status == 200) {
                wx.requestPayment({
                    'timeStamp': res.data.timeStamp,
                    'nonceStr': res.data.nonceStr,
                    'package': res.data.package,
                    'signType': res.data.signType,
                    'paySign': res.data.paySign,
                    'success': function (res) {
                        common.showToast('支付成功', 'success')
                        wx.navigateTo({
                            url: '/pages/ScenicArea/ScenicAreaCommitPage/paySuccess/index?payment='
                                + that.data.totalPrice +
                                '&orderId=' + orderId +
                                '&cardId=' + that.data.cardId,
                        })
                    },
                    'fail': function (res) {
                        if (res.errMsg === 'requestPayment:fail cancel') {
                            if (that.data.cardId == '') {//景区
                                wx.redirectTo({
                                    url: '/pages/ScenicArea/ScenicAreaOrder/index?status=1',
                                })
                            } else { //会员卡
                                wx.redirectTo({
                                    url: '/pages/ScenicArea/NianCardOrder/index?status=1',
                                })
                            }

                        } else {
                            common.showToast(res.errMsg)
                        }
                    }
                })
            } else {
                common.showToast(res.msg)
            }

        })

    },
    toAddBuyer() {
        wx.navigateTo({
            url: '/pages/ScenicArea/ScenicAreaAddBuyer/index',
        })
    },
    addBuyer() {
        this.setData({
            showBuyerPanel: true
        })
    },
    editBuyer(e) {
        let {
            item
        } = e.currentTarget.dataset
        console.log(item)

        wx.navigateTo({
            url: '/pages/ScenicArea/ScenicAreaAddBuyer/index?buyerInfo=' + JSON.stringify(item),
        })
    },
    closeBuyerPanel() {
        this.setData({
            showBuyerPanel: false
        })
    },
    openCouponsPanel() {
        this.setData({
            showCouponsPanel: true
        })
    },
    closeCouponsPanel() {
        this.setData({
            showCouponsPanel: false
        })
    }
})